package br.com.listadecompras.activities;

import java.util.ArrayList;
import java.util.LinkedList;

import br.com.listadecompras.DAO.GroupDAO;
import br.com.listadecompras.DAO.ItemDAO;
import br.com.listadecompras.model.Item;
import br.com.listadecompras.utils.Constantes;
import br.com.listadecompras.utils.DBHelper;
import br.com.listadecompras.utils.DialogHelper;
import br.com.listadecompras.utils.ItemArrayAdapter;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class ListaDeComprasActivity extends Activity {
	
	private ListView listView;
	private ItemArrayAdapter adapter;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        LinkedList<Item> list = null;
        
        this.listView = (ListView) this.findViewById(R.id.lstViewItens);
        this.listView.setTextFilterEnabled(true);
        this.setOnClickListView();
       
        DBHelper db = new DBHelper(this, Constantes.DataBaseConstantes.DATABASE_NAME);
        
        try {        	
        	this.createTables(db.getWritableDatabase());
        	
        	ItemDAO itemDAO = new ItemDAO(db.getReadableDatabase());
        	
        	ArrayList<Item> itens = itemDAO.getTodosItens();
        	
        	if (itens.size() > 0) {
        		
				list = new LinkedList<Item>();
        		
        		for (Item item : itens) {
        			list.add( item );
				}
        		
        		this.adapter = new ItemArrayAdapter(this, R.layout.list_view_row, list);
        		this.listView.setAdapter(this.adapter);
        		
        	} else {
        		this.adapter = new ItemArrayAdapter(this, R.layout.list_view_row);
        	}

        } catch (Exception e) {
        	new AlertDialog.Builder(this)
    		.setMessage(e.toString())
    		.setTitle("ERRO")
    		.setNeutralButton("OK", new DialogInterface.OnClickListener() {					
				public void onClick(DialogInterface arg0, int arg1) {}
			})
			.show();
        	
		} finally {
			db.close();
			list = null;
		}
    }
    
    public void callAddItem(View view) {
    	Intent intent = new Intent(this.getApplicationContext(), AdicionarItemActivity.class);
    	startActivityForResult(intent, AdicionarItemActivity.CODIGO_ACTIVITY);
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	super.onActivityResult(requestCode, resultCode, data);
    	
    	if (data != null) { 
    		Resources res = this.getResources();
    		
	    	switch (requestCode) {
			case AdicionarItemActivity.CODIGO_ACTIVITY:
				if (insertItemDataBase( adicionaItemNaLista(data) ))
					DialogHelper.showDialog(this, 
											   res.getString(R.string.dialogTitleWarning), 
											   res.getString(R.string.dialogItemInseridoSucesso), 
											   res.getString(R.string.dialogOkOption));
				else
					DialogHelper.showDialog(this, 
											   res.getString(R.string.dialogTitleWarning),
											   res.getString(R.string.dialogProblemaInserirItem),
											   res.getString(R.string.dialogOkOption));
				break;
			default:
				break;
			}
    	}
    }
    
    private Item adicionaItemNaLista(Intent data) {
    	
    	Bundle extras = data.getExtras();
    	
    	String nomeNovoItem = extras.getString(Item.NOME);
    	String descricaoNovoItem = extras.getString(Item.DESCRICAO);
    	
    	Item item = new Item(nomeNovoItem, descricaoNovoItem);
    	
    	adapter.add(item);
    	
    	this.listView.setAdapter(this.adapter);
    	
    	return item;
    }
    
    private boolean insertItemDataBase(Item item) {
    	
    	DBHelper db = new DBHelper(this, Constantes.DataBaseConstantes.DATABASE_NAME);
    	
    	try {
    		ItemDAO itemDAO = new ItemDAO(db.getWritableDatabase());
    		boolean result = itemDAO.insertItem(item);;
    		
    		return result;
    				
    	} catch (Exception e) {
			return false;
			
		} finally {
			db.close();
			
		}
    }
    
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
    	super.onConfigurationChanged(newConfig);
    	setContentView(R.layout.main);
    	
    	this.listView = (ListView) this.findViewById(R.id.lstViewItens);
    	this.listView.setTextFilterEnabled(true);
        this.setOnClickListView();
        
    	this.listView.setAdapter(this.adapter);
    }
    
    private void setOnClickListView() {
    
    	this.listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapter, View view, int position,
					long arg3) {
				
				Item item = (Item)listView.getItemAtPosition(position);
				
				Intent intent = new Intent(getApplicationContext(), ViewItemActivity.class);
				
				intent.putExtra(Item.NOME, item.getNome());
				intent.putExtra(Item.DESCRICAO, item.getDescricao());
				
				startActivity(intent);
			}
		});
    }
    
    private void createTables(SQLiteDatabase sqlite) throws SQLiteException {
    	
    	try {
	    	sqlite.execSQL(ItemDAO.CREATE_TABLE);
	    	sqlite.execSQL(GroupDAO.CREATE_TABLE);
	    	sqlite.execSQL(Constantes.DataBaseConstantes.AuxTables.CREATE_TABLE_GROUP_ITENS);
	    	
    	} catch (SQLiteException e) {
			throw e;
		}
    	
    }
    
   public void callAddGroup(View view) {
    	Intent intent = new Intent(this.getApplicationContext(), CriaGrupoActivity.class);
    	this.startActivity(intent);
    }
}